package com.niit.agricstore.controller;

import com.niit.agricstore.entity.Picture;
import com.niit.agricstore.service.PictureService;
import com.niit.agricstore.util.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/pic")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    // 根据 productID 查询图片
    @GetMapping("/byProduct/{productId}")
    public List<Picture> getImagesByProductId(@PathVariable Long productId) {
        return pictureService.getImagesByProductId(productId);
    }

    // 根据 ID 查询图片
    @GetMapping("/main/{id}")
    public Result<Picture> getImageById(@PathVariable Long id) {
        Picture picture = pictureService.getMainImageById(id);
        if(picture!=null){
            return Result.success(picture);
        }
        else return Result.error("423","头像查询失败");
    }

    // 上传图片
    @PostMapping("/upload")
    public Picture uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("productId") Long productId) {
        try {
            return pictureService.uploadImage(file, productId);
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to upload image");
        }
    }

    // 删除图片
    @DeleteMapping("/{id}")
    public void deleteImage(@PathVariable Long id) {
        pictureService.deleteImage(id);
    }
}